package com.trf.servlet.user;

import com.alibaba.fastjson.JSONArray;
import com.mysql.cj.util.StringUtils;
import com.trf.pojo.Role;
import com.trf.pojo.User;
import com.trf.service.role.RoleServiceIml;
import com.trf.service.user.UserServiceImpl;
import com.trf.util.Constants;
import com.trf.util.PageSupport;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;

/**
 * @author 唐荣锋
 * @Date 2022/3/10-星期四-17:26
 */
//实现Servlet复用
public class UserServlet extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //复用提取方法
        String method = req.getParameter("method");
        if (method.equals("savepwd")&&method!=null){
            this.updatePwd(req,resp);
        }else if (method.equals("pwdmodify")&&method!=null){
            this.pwdModify(req,resp);
        }else if (method.equals("query")&&method!=null){
            this.query(req,resp);
        }


    }

    //query方法：查询客户列表
    private void query(HttpServletRequest req, HttpServletResponse resp) {
        //从前端获取数据
        String queryUserName = req.getParameter("queryName");
        String temp = req.getParameter("queryUserRole");
        String pageIndex = req.getParameter("pageIndex");

        int queryUserRole = 0;

        //获取客户列表
        UserServiceImpl userService = new UserServiceImpl();
        List<User> userList = null;

        //第一次请求，一定是第一页，页面大小固定
        int pageSize = 5;//前期配置，后期可根据实际情况更改
        int currentPageNo = 1;

        if (queryUserName==null){
            queryUserName = "";
        }
        if (temp!=null&&!temp.equals("")){
            //给查询赋值！0，1，2，3
            queryUserRole = Integer.parseInt(temp);
        }
        if (pageIndex!=null){
             currentPageNo = Integer.parseInt(pageIndex);
        }

        //获取用户的总数（分页：上下页的情况）
        int totalCount = userService.getUserCount(queryUserName, queryUserRole);
        //总页支持
        PageSupport pageSupport = new PageSupport();
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(totalCount);

        int totalPageCount = ((int)(totalCount/pageSize))+1;

        //控制首页和尾页
        //如果页面要小于1了，就显示第一页的东西
        if (currentPageNo<1){
            currentPageNo = 1;
        }else if (currentPageNo>totalPageCount){//当前页面大于了最后一页
            currentPageNo = totalPageCount;

        }

        //获取用户列表展示
         userList = userService.getUserList(queryUserName, queryUserRole, currentPageNo, pageSize);
         req.setAttribute("userList",userList);

         RoleServiceIml roleService = new RoleServiceIml();
         List<Role> roleList = roleService.getRoleList();
         req.setAttribute("roleList",roleList);
         req.setAttribute("totalCount",totalCount);
         req.setAttribute("currentPageNo",currentPageNo);
         req.setAttribute("totalPageCount",totalPageCount);
         req.setAttribute("queryUserName",queryUserName);
         req.setAttribute("queryUserRole",queryUserRole);

         //返回前端
        try {
            req.getRequestDispatcher("userlist.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }


    //修改密码
    public void updatePwd(HttpServletRequest req, HttpServletResponse resp){
        //从Session里面拿ID;
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        //从前端拿到新密码
        String newpassword = req.getParameter("newpassword");


//    调试节点    System.out.println("UserServlet:"+newpassword);

        boolean flag = false;

        //!StringUtils.isNullOrEmpty(newpassword):解释为：如果newpassword不为空，或不为0，说明用户设置了新密码
        if (o!=null&& newpassword!=null &&newpassword.length()!=0){

            //调用Service层
            UserServiceImpl userService = new UserServiceImpl();
            //登录获取密码
            flag = userService.updatePwd(((User) o).getId(), newpassword);
            if (flag){//如果登录成功
                req.setAttribute("message","修改密码成功，请退出，使用新密码登录");
                //修改密码成功，移除当前Session，由过滤器等到强制退出
                req.getSession().removeAttribute(Constants.USER_SESSION);
            }else {
                req.setAttribute("message","密码修改失败");

            }
        }else {
            req.setAttribute("message","新密码有问题");
        }
        //跳转
        try {
            req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //验证旧密码，Session中有用户的旧密码
    public void pwdModify(HttpServletRequest req, HttpServletResponse resp){
        //从Session里面拿ID;
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        //从前端拿到新密码
        String oldpassword = req.getParameter("oldpassword");

        //万能的Map(一切的东西都会用map):结果集
        HashMap<String, String> resultMap = new HashMap<String, String>();


        if (o==null){//Session失效了，Session过期了
            resultMap.put("result","sessionerror");
        }else if (StringUtils.isNullOrEmpty(oldpassword)){//输入的密码为空
            resultMap.put("result","error");
        }else {
            String userPassword = ((User) o).getUserPassword();
            if (oldpassword.equals(userPassword)){
                resultMap.put("result","true");
            }else {
                resultMap.put("result","false");
            }
        }

        try {
            resp.setContentType("application/json");//限定格式
            PrintWriter writer = resp.getWriter();
            //JSONArray 阿里巴巴的JSON工具类，转换格式
            /*
            resultMap = ["result","sessionerror","result","error"]
            Json格式 = {key:value}
             */
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();//刷新
            writer.close();//关闭
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
